#include "SWFMasterWindow.h"
#include "ui_SWFMasterWindow.h"
#include <QStandardItem>
#include <QIcon>
#include <QVariant>
#include <QFileDialog>
#include "swf/SWFTag.h"
#include "swf/SWF.h"
#include "swf/SWFWriter.h"
#include "swf/SWFTagFactory.h"
#include "swf/SWFDecoder.h"
#include "swf/tags/TagDoABC.h"
#include "swf/abc/ABCFile.h"
#include "swf/abc/AS3Model.h"
#include "editor/Icon.h"
#include "editor/EditorContainer.h"
#include "editor/DoABCEditor.h"
#include "editor/model/TagTreeItem.h"
#include "editor/model/SWFTreeModel.h"
#include "editor/model/DoABCTreeItem.h"
#include "editor/MetaDataEditor.h"

SWFMasterWindow::SWFMasterWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::SWFMasterWindow),
	_swf(nullptr)
{
    ui->setupUi(this);

    _swfObjectModel = new SWFTreeModel();

    ui->itemTree->setModel(_swfObjectModel);
	ui->itemTree->setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu);
	_editorContainer = new EditorContainer();
	ui->horizontalLayout_2->addWidget(_editorContainer);
}

SWFMasterWindow::~SWFMasterWindow()
{
    delete ui;
}

void SWFMasterWindow::onOpen()
{
	if (_swf != nullptr)
		return;//TODO: message box

	QString fileName = QFileDialog::getOpenFileName(this, "Select SWF", "", "SWF(*.swf)");
	if (!QFile::exists(fileName))
		return;//TODO: message box
	
	SWFDecoder decoder;
	_swf = decoder.decode(fileName.toStdString());
	AS3SWF* as3swf = new AS3SWF(_swf);
	std::vector<AS3ABCFile*> abcVec;
	as3swf->getAllABCFiles(abcVec);

	auto item = new SWFTreeItem("DoABC");
	for (auto abc : abcVec)
	{
		auto child = new DoABCTreeItem(abc);
		item->appendRow(child);
	}
	_swfObjectModel->appendRow(item);

	item = new SWFTreeItem("Tags");
	for (auto tag : _swf->tags)
	{
		auto child = new TagTreeItem(tag);
		item->appendRow(child);
	}
	_swfObjectModel->appendRow(item);
}

void SWFMasterWindow::onSaveAs()
{
	QString fileName = QFileDialog::getSaveFileName(this, "Save SWF", "", "SWF(*.swf)");
	if (fileName.isEmpty() == false)
	{
		SWFWriter w;
		w.write(_swf, fileName.toStdString());
	}
}

void SWFMasterWindow::onItemTreeContextMenuRequested( const QPoint& pos )
{
	auto index = ui->itemTree->currentIndex();
	auto item = _swfObjectModel->itemFromIndex(index);
	QMenu* menu = item->requestContextMenu();
	if (menu != nullptr)
	{
		menu->exec(QCursor::pos());
	}
}

void SWFMasterWindow::onItemTreeSelectItem( const QModelIndex& index )
{
	auto model = _swfObjectModel->itemFromIndex(index);
	if (model)
	{
		_editorContainer->openEditor(model);
	}
}

void SWFMasterWindow::onAbout()
{

}
